package com.soft.collateral.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.soft.collateral.entity.*;
import com.soft.collateral.mapper.*;
import com.soft.collateral.service.WithdrawService;
import com.soft.collateral.vo.PageQueryVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class WithdrawServiceImpl extends ServiceImpl<WithdrawApplyMapper, WithdrawApply> implements WithdrawService {

    @Autowired
    private WithdrawApplyMapper withdrawApplyMapper;
    @Autowired
    private WithdrawApplyDetailMapper withdrawApplyDetailMapper;
    @Autowired
    private WithdrawApprovalMapper withdrawApprovalMapper;
    @Autowired
    private StorageWithdrawRecordMapper storageWithdrawRecordMapper;
    @Autowired
    private CollateralMapper collateralMapper;
    @Autowired
    private CollateralTypeMapper collateralTypeMapper;
    @Autowired
    private CollateralDetailMapper collateralDetailMapper;
    @Autowired
    private CollateralPicMapper collateralPicMapper;

    @Override
    public List<WithdrawApply> listAll() {
        List<WithdrawApply> withdrawApplies = withdrawApplyMapper.selectList(null);
        withdrawApplies.forEach(this::loadDetails);
        return withdrawApplies;
    }

    @Override
    public Page<WithdrawApply> pageQuery(PageQueryVO pageQueryVO) {
        Page<WithdrawApply> page = new Page<>(pageQueryVO.getCurrentPage(), pageQueryVO.getPageSize());
        LambdaQueryWrapper<WithdrawApply> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasLength(pageQueryVO.getQueryString())) {
            wrapper.like(WithdrawApply::getApplyUser, pageQueryVO.getQueryString())
                    .or()
                    .like(WithdrawApply::getPurpose, pageQueryVO.getQueryString());
        }
        // 添加状态过滤条件
        if (pageQueryVO.getStatus() != null) {
            wrapper.eq(WithdrawApply::getStatus, pageQueryVO.getStatus());
        }
        Page<WithdrawApply> withdrawApplyPage = withdrawApplyMapper.selectPage(page, wrapper);
        withdrawApplyPage.getRecords().forEach(this::loadDetails);
        return withdrawApplyPage;
    }

    @Override
    @Transactional
    public boolean saveWithdrawApply(WithdrawApply withdrawApply) {
        // 保存申请基本信息
        boolean saved = withdrawApplyMapper.insert(withdrawApply) > 0;
        if (saved && withdrawApply.getDetails() != null && !withdrawApply.getDetails().isEmpty()) {
            // 保存申请明细
            for (WithdrawApplyDetail detail : withdrawApply.getDetails()) {
                detail.setApplyId(withdrawApply.getApplyId());
                withdrawApplyDetailMapper.insert(detail);
            }
        }
        return saved;
    }

    @Override
    public WithdrawApply getByIdWithDetails(Integer id) {
        WithdrawApply withdrawApply = withdrawApplyMapper.selectById(id);
        if (withdrawApply != null) {
            loadDetails(withdrawApply);
        }
        return withdrawApply;
    }

    @Override
    @Transactional
    public boolean updateWithdrawApply(WithdrawApply withdrawApply) {
        // 1. 更新基本信息
        boolean updated = withdrawApplyMapper.updateById(withdrawApply) > 0;

        // 2. 更新明细信息（先删后增）
        if (updated) {
            withdrawApplyDetailMapper.delete(new LambdaQueryWrapper<WithdrawApplyDetail>()
                    .eq(WithdrawApplyDetail::getApplyId, withdrawApply.getApplyId()));

            if (withdrawApply.getDetails() != null) {
                for (WithdrawApplyDetail detail : withdrawApply.getDetails()) {
                    detail.setApplyId(withdrawApply.getApplyId());
                    withdrawApplyDetailMapper.insert(detail);
                }
            }
        }
        return updated;
    }

    @Override
    @Transactional
    public boolean removeByIdWithDetails(Integer id) {
        // 删除审核记录
        withdrawApprovalMapper.delete(new LambdaQueryWrapper<WithdrawApproval>()
                .eq(WithdrawApproval::getApplyId, id));
        // 删除明细
        withdrawApplyDetailMapper.delete(new LambdaQueryWrapper<WithdrawApplyDetail>()
                .eq(WithdrawApplyDetail::getApplyId, id));
        // 删除基本信息
        return withdrawApplyMapper.deleteById(id) > 0;
    }

    @Override
    @Transactional
    public boolean approveWithdrawApply(WithdrawApproval approval) {
        // 1. 保存审核记录
        boolean saved = withdrawApprovalMapper.insert(approval) > 0;

        if (saved) {
            // 2. 更新申请状态
            WithdrawApply apply = new WithdrawApply();
            apply.setApplyId(approval.getApplyId());
            apply.setStatus(approval.getApprovalResult() == 1 ? 1 : 2); // 1:已通过,2:已拒绝
            withdrawApplyMapper.updateById(apply);

            // 3. 如果审核通过，创建出库记录
            if (approval.getApprovalResult() == 1) {
                WithdrawApply withdrawApply = getByIdWithDetails(approval.getApplyId());
                if (withdrawApply != null && withdrawApply.getDetails() != null) {
                    for (WithdrawApplyDetail detail : withdrawApply.getDetails()) {
                        StorageWithdrawRecord record = new StorageWithdrawRecord();
                        record.setCollateralId(detail.getCollateralId());
                        record.setRecordType(2); // 2:出库
                        record.setRelatedApplyId(approval.getApplyId());
                        record.setOperationTime(LocalDateTime.now());
                        record.setOperator(approval.getApprover());

                        // 根据出库类型设置状态
                        int status = 2; // 2:出库状态
                        if (withdrawApply.getApplyType() == 3) { // 临时出库
                            status = 3; // 3:临时出库状态
                        }
                        record.setCurrentStatus(status);

                        storageWithdrawRecordMapper.insert(record);

                        // 更新押品状态
                        Collateral collateral = new Collateral();
                        collateral.setCollateralId(detail.getCollateralId());
                        collateral.setStatus(status);
                        collateralMapper.updateById(collateral);
                    }
                }
            }
        }
        return saved;
    }

    private void loadDetails(WithdrawApply withdrawApply) {
        // 加载明细信息
        List<WithdrawApplyDetail> details = withdrawApplyDetailMapper.selectList(
                new LambdaQueryWrapper<WithdrawApplyDetail>()
                        .eq(WithdrawApplyDetail::getApplyId, withdrawApply.getApplyId()));

        // 加载押品信息
        details.forEach(detail -> {
            if (detail.getCollateralId() != null) {
                Collateral collateral = collateralMapper.selectById(detail.getCollateralId());
                if (collateral != null) {
                    loadDetails(collateral);
                }
                detail.setCollateral(collateral);
            }
        });

        withdrawApply.setDetails(details);

        // 加载审核信息
        WithdrawApproval approval = withdrawApprovalMapper.selectOne(
                new LambdaQueryWrapper<WithdrawApproval>()
                        .eq(WithdrawApproval::getApplyId, withdrawApply.getApplyId()));
        withdrawApply.setApproval(approval);
    }

    private void loadDetails(Collateral collateral) {
        // 加载类型信息
        if (collateral.getTypeId() != null) {
            collateral.setCollateralType(collateralTypeMapper.selectById(collateral.getTypeId()));
        }
        // 加载详细信息
        CollateralDetail detail = collateralDetailMapper.selectOne(
                new LambdaQueryWrapper<CollateralDetail>()
                        .eq(CollateralDetail::getCollateralId, collateral.getCollateralId()));
        collateral.setCollateralDetail(detail);
        // 加载图片信息
        List<CollateralPic> pics = collateralPicMapper.selectList(
                new LambdaQueryWrapper<CollateralPic>()
                        .eq(CollateralPic::getCollateralId, collateral.getCollateralId())
                        .orderByAsc(CollateralPic::getId));
        collateral.setCollateralPic(pics);
    }
}